package com.sl.eurekaserver.command;

import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixRequestCache;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
import com.sl.eurekaserver.entity.User;

/**
 * 同步执行 ： User user = new UserCommand(restTemplate, "xxx").execute()
 * 异步执行： Future<User> future = new UserCommand(restTemplate, "xxx").queue()      
 * 
 * @author 舒莉
 *
 */
public class UserCommand extends HystrixCommand<User>{
	
	private static final HystrixCommandKey GETTER_KEY = HystrixCommandKey.Factory
			.asKey("CommandKey");
	
	private RestTemplate restTemplate;
	
	private String userName;

	public UserCommand(RestTemplate restTemplate, String userName) {
		// 最少配置:指定命令组名(CommandGroup)
		super(Setter.withGroupKey(
				HystrixCommandGroupKey.Factory.asKey("GetSetGet"))
				.andCommandKey(GETTER_KEY));
		this.restTemplate = restTemplate;
		this.userName = userName;
	}

	@Override
	protected User run() throws Exception {
		return restTemplate.getForObject("http://HELLO-SERVICE/hello/{userName}",
				User.class, userName);
	}

	@Override
	protected User getFallback() {
		 return new User();
	}

	@Override
	protected String getCacheKey() {
		return userName;
	}
	
	public static void flushCache(String userName){
		HystrixRequestCache.getInstance(GETTER_KEY, HystrixConcurrencyStrategyDefault.getInstance()).clear(userName);
	}
}

